<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Config as ConfigModel;
use app\common\model\Area as AreaModel;
use app\common\model\Version;
use think\captcha\Captcha;
use think\Config;
use think\Hook;
use think\Db;

/**
 * 公共接口
 */
class Common extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    public function _initialize()
    {

        if (isset($_SERVER['HTTP_ORIGIN'])) {
            header('Access-Control-Expose-Headers: __token__');//跨域让客户端获取到
        }
        //跨域检测
        check_cors_request();

        if (!isset($_COOKIE['PHPSESSID'])) {
            Config::set('session.id', $this->request->server("HTTP_SID"));
        }
        parent::_initialize();
    }

    /*
     * 搜索热词
     * @path api/common/getHotWords
     * */
    public function getHotWords()
    {
        $where = "id > 0";
        $field = "id,name";
        $order = "weigh DESC,add_time DESC";
        $list = Db::name("searchkey")->where($where)->field($field)->order($order)->select();
        $this->success("请求成功",$list);
    }

    /*
     * 配置信息
     * @path api/common/getBasicConfig
     * */
    public function getBasicConfig()
    {
        $list = ConfigModel::all();
        $info = $this->getArrayData($list);
        if($info["wxcode"]){
            $info["wxcode"] = splicing_domain($info["wxcode"]);
        }
        if($info["about_img"]){
            $info["about_img"] = splicing_domain($info["about_img"]);
        }
        if($info["about"]){
            $info["about"]=get_image_url($info["about"],protocol_name() . '://' . $_SERVER['SERVER_NAME']);
        }
        $this->success("请求成功",$info);
    }

    public function getArrayData($data)
    {
        if (!isset($data['value'])) {
            $result = [];
            foreach ($data as $index => $datum) {
                $result['field'][$index] = $datum['name'];
                $result['value'][$index] = $datum['value'];
            }
            $data = $result;
        }
        $field = isset($data['field']) ? $data['field'] : (isset($data['key']) ? $data['key'] : []);
        $value = isset($data['value']) ? $data['value'] : [];
        foreach ($field as $m => $n) {
            if ($n != '') {
                $field_arr[] = $field[$m];
                $value_arr[] = $value[$m];
            }
        }
        return $field_arr ? array_combine($field_arr, $value_arr) : [];
    }

    /*
     * 省市区联动
     * @path api/common/region
     * @param type 1:省 2.市 3.区
     * */
    public function region()
    {
        $type = $this->request->param('type',1);
        $id = $this->request->param('id');
        if ($type=='1') {
            $list = AreaModel::where('pid', '0')->field('id,name')->select();
        } else {
            $list =AreaModel::where('pid', $id)->field('id,name')->select();
        }
        $this->success("请求成功",$list);
    }

    /**
     * 加载初始化
     * @param string $version 版本号
     * @param string $lng 经度
     * @param string $lat 纬度
     */
    public function init()
    {
        if ($version = $this->request->request('version')) {
            $lng = $this->request->request('lng');
            $lat = $this->request->request('lat');

            //配置信息
            $upload = Config::get('upload');
            //如果非服务端中转模式需要修改为中转
            if ($upload['storage'] != 'local' && isset($upload['uploadmode']) && $upload['uploadmode'] != 'server') {
                //临时修改上传模式为服务端中转
                set_addon_config($upload['storage'], ["uploadmode" => "server"], false);

                $upload = \app\common\model\Config::upload();
                // 上传信息配置后
                Hook::listen("upload_config_init", $upload);

                $upload = Config::set('upload', array_merge(Config::get('upload'), $upload));
            }

            $upload['cdnurl'] = $upload['cdnurl'] ? $upload['cdnurl'] : cdnurl('', true);
            $upload['uploadurl'] = preg_match("/^((?:[a-z]+:)?\/\/)(.*)/i", $upload['uploadurl']) ? $upload['uploadurl'] : url($upload['storage'] == 'local' ? '/api/common/upload' : $upload['uploadurl'], '', false, true);

            $content = [
                'citydata'    => AreaModel::getCityFromLngLat($lng, $lat),
                'versiondata' => Version::check($version),
                'uploaddata'  => $upload,
                'coverdata'   => Config::get("cover"),
            ];
            $this->success('', $content);
        } else {
            $this->error(__('Invalid parameters'));
        }
    }

    /**
     * 图形验证码
     * @param $id
     * @path api/common/captcha
     */
    public function captcha($id = "")
    {
        Config::set([
            'captcha' => array_merge(config('captcha'), [
                'fontSize' => 44,
                'imageH'   => 150,
                'imageW'   => 350,
            ])
        ]);
        $captcha = new Captcha((array)Config::get('captcha'));
        return $captcha->entry($id);
    }

}
